package com.ourteam.config;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class ServiceHandlerInterceptor implements HandlerInterceptor {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(ServiceHandlerInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		//response.addHeader("Access-Control-Allow-Origin", "*");
		// 响应类型
		//response.addHeader("Access-Control-Allow-Methods", "POST,GET");
		// 响应头设置
		//response.addHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

		if (logger.isInfoEnabled()) {

			long startTime = System.currentTimeMillis();

			request.setAttribute("_startTime", startTime);
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		if (logger.isInfoEnabled()) {

			long startTime = (Long) request.getAttribute("_startTime");

			request.removeAttribute("_startTime");

			long endTime = System.currentTimeMillis();

			ByteArrayOutputStream output = new ByteArrayOutputStream();

			PrintStream printStream = new PrintStream(output);

			printStream.print(request.getRequestURI());

			printStream.print(" : {");

			Map<String, String[]> parameters = request.getParameterMap();

			for (Iterator<String> iterator = request.getParameterMap().keySet().iterator(); iterator.hasNext();) {
				String key = iterator.next();
				printStream.print(key);
				printStream.print("=[");
				printStream.print(StringUtils.join(parameters.get(key), ","));
				printStream.print("] ");
			}

			printStream.print("} ->");

			printStream.print(endTime - startTime);

			printStream.print(" ms");

			logger.info(output.toString("UTF-8"));
			
		}

	}

}
